<template>
  <div class="node-area">
    <HeaderSearch class="header-search">
      <template>
        <el-form class="search-from" label-position="left" :inline="true">
          <el-form-item label="点位搜索：" class="area-search">
            <el-input v-model="name" placeholder="请输入" clearable></el-input>
          </el-form-item>
          <el-form-item label="区域搜索：" class="area-search">
            <el-select v-model="area" clearable placeholder="请选择">
              <el-option
                v-for="item in options.currentPageRecords"
                :key="item.id"
                :label="item.name"
                :value="item.id"
              >
              </el-option>
            </el-select>
          </el-form-item>
          <el-form-item class="search-btn">
            <el-button
              plain
              icon="el-icon-search"
              class="btn"
              @click="getAreaList"
              >查询</el-button
            >
          </el-form-item>
        </el-form>
      </template>
    </HeaderSearch>
    <TableContent
      ref="TableContent"
      :params="params"
      :tableData="tableData"
      :areaList="areaList"
    >
      <template #addBtn>
        <el-col class="col-btn">
          <el-button
            type="info"
            icon="el-icon-circle-plus-outline"
            @click="changeArea('add')"
            >新建</el-button
          >
        </el-col>
      </template>
      <template #operate="{ row }">
        <el-button type="text" size="small" @click="check(row.id)">
          查看详情
        </el-button>
        <el-button type="text" size="small" @click="changeArea('edit', row)">
          修改
        </el-button>
        <el-button
          type="text"
          size="small"
          style="color: red"
          @click="delArea(row.id)"
        >
          删除
        </el-button>
      </template>
    </TableContent>
    <CheckDialog ref="CheckDialog" title="区域详情">
      <template #content>
        <el-row>
          <el-col :span="24">
            <el-table :data="areaDetails">
              <el-table-column
                type="index"
                label="序号"
                align="center"
              ></el-table-column>
              <el-table-column
                prop="innerCode"
                label="机器编号"
                align="center"
              ></el-table-column>
              <el-table-column prop="vmStatus" label="设备状态" align="center">
                <template #default="{ row }">
                  {{ row.vmStatus | vmStatus }}
                </template>
              </el-table-column>
              <el-table-column
                prop="lastSupplyTime"
                label="最后一次供货时间"
                align="center"
              >
                <template #default="{ row }">
                  {{ row.lastSupplyTime | formatDate }}
                </template>
              </el-table-column>
            </el-table>
          </el-col>
        </el-row>
      </template>
    </CheckDialog>
    <AddOrEdit ref="AddOrEdit" :title="title" @addArea="addArea">
      <template #formDialog>
        <el-form
          ref="form"
          :model="form"
          :rules="rules"
          label-position="left"
          label-width="110px"
        >
          <el-form-item label="点位名称：" prop="name">
            <el-input
              v-model="form.name"
              placeholder="请输入"
              maxlength="15"
              show-word-limit
            ></el-input>
          </el-form-item>
          <el-form-item label="所在区域：" prop="regionId">
            <el-select v-model="form.regionId" clearable placeholder="请选择">
              <el-option
                v-for="item in options.currentPageRecords"
                :key="item.id"
                :label="item.name"
                :value="item.id"
              >
              </el-option>
            </el-select>
          </el-form-item>
          <el-form-item label="所属商圈：" prop="businessId">
            <el-select v-model="form.businessId" clearable placeholder="请选择">
              <el-option
                v-for="item in businessId"
                :key="item.id"
                :label="item.name"
                :value="item.id"
              >
              </el-option>
            </el-select>
          </el-form-item>
          <el-form-item label="归属合作商：" prop="ownerName">
            <el-select v-model="form.ownerName" clearable placeholder="请选择">
              <el-option
                v-for="item in ownerName"
                :key="item.name"
                :label="item.name"
                :value="item.name"
              >
              </el-option>
            </el-select>
          </el-form-item>
          <el-form-item label="详细地址：" prop="addr">
            <el-cascader
              popper-class="location"
              :options="addressData"
              v-model="form.addr"
              :props="{ expandTrigger: 'click' }"
              placeholder="请选择"
            ></el-cascader>
          </el-form-item>
          <el-form-item label="备注说明：" prop="remark">
            <el-input
              type="textarea"
              v-model="form.remark"
              placeholder="请输入"
              maxlength="60"
              show-word-limit
            ></el-input>
          </el-form-item>
        </el-form>
      </template>
    </AddOrEdit>
  </div>
</template>

<script>
import { regionData, CodeToText, TextToCode } from 'element-china-area-data'
import HeaderSearch from '../components/HeaderSearch'
import TableContent from '../components/TableContent'
import CheckDialog from '../components/CheckDialog'
import AddOrEdit from '../components/AddOrEdit'
import {
  getNodeList,
  delNode,
  checkNode,
  addArea,
  editNode,
  getAreaList,
  getBusinessType,
  getPartner
} from '@/api/point'
export default {
  name: 'Dkd2Point',

  components: {
    HeaderSearch,
    TableContent,
    CheckDialog,
    AddOrEdit
  },
  data () {
    return {
      // 选择器
      options: {},
      // 商圈
      businessId: [],
      // 合作商
      ownerName: [],
      // 城市列表
      addressData: regionData,
      // 地区查询
      area: '',
      // 点位查询
      name: '',
      // 分页
      params: {
        pageIndex: 1,
        pageSize: 10
      },
      // 表格数据
      tableData: {},
      // 表头
      areaList: {
        name: '点位名称',
        'region.name': '所在区域',
        'businessType.name': '商圈类型',
        ownerName: '合作商',
        add: '详细地址'
      },
      // 区域详情
      areaDetails: [],
      // 表单标题
      title: '',
      // 表单
      form: {
        createUserId: 1
      },
      // 规则
      rules: {
        name: [{ required: true, message: '请输入', trigger: 'blur' }],
        regionId: [{ required: true, message: '请输入', trigger: 'change' }],
        businessId: [{ required: true, message: '请输入', trigger: 'change' }],
        ownerName: [{ required: true, message: '请输入', trigger: 'change' }],
        addr: [{ required: true, message: '请输入', trigger: 'change' }],
        remark: [{ required: true, message: '请输入', trigger: 'blur' }]
      }
    }
  },

  mounted () {
    this.getAreaList()
    this.getOptions()
  },

  filters: {
    vmStatus (val) {
      if (val === 0) {
        return '未投放'
      } else if (val === 1) {
        return '运营'
      } else if (val === 3) {
        return '撤机'
      }
    },
    formatDate (val) {
      return val.split('T').join(' ')
    }
  },

  methods: {
    // 获取选择器数据
    async getOptions () {
      const res = await getAreaList({
        pageIndex: 1,
        pageSize: 10000
      })
      this.options = res
    },
    // 获取表格数据
    async getAreaList () {
      let res
      try {
        this.$refs.TableContent.loading = true
        if (this.area || this.name) {
          res = await getNodeList({
            ...this.params,
            name: this.name,
            regionId: this.area
          })
        } else {
          res = await getNodeList(this.params)
        }
      } finally {
        this.$refs.TableContent.loading = false
      }
      if (res.currentPageRecords.length <= 0 && this.params.pageIndex > 1) {
        this.params.pageIndex--
        this.getAreaList()
      }
      res.currentPageRecords.forEach((ele) => {
        ele.add = ele.addr.split('-')[ele.addr.split('-').length - 1]
      })
      this.tableData = res
    },
    // 删除数据
    async delArea (id) {
      this.$confirm('是否要删除该区域, 是否继续?', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(async () => {
        try {
          await delNode(id)
          this.$message.success('区域删除成功')
          this.getAreaList()
        } catch (err) {
          this.$message.error(err.response.data)
        }
      })
    },
    // 查看详情
    async check (id) {
      this.$refs.CheckDialog.visible = true
      const res = await checkNode(id)
      this.areaDetails = res
    },
    // 新增或修改
    async changeArea (val, row) {
      this.businessId = await getBusinessType()
      const res = await getPartner()
      this.ownerName = res.currentPageRecords
      if (val === 'add') {
        this.title = '新增点位'
      } else {
        this.title = '修改点位'
        this.form = {
          id: row.id,
          areaCode: row.areaCode,
          businessId: row.businessId,
          ownerId: row.ownerId,
          name: row.name,
          ownerName: row.ownerName,
          regionId: row.regionId,
          remark: row.add,
          createUserId: 1
        }
        const arr = row.addr.split('-')
        this.form.addr = [
          TextToCode[arr[0]].code,
          TextToCode[arr[0]][arr[1]].code,
          TextToCode[arr[0]][arr[1]][arr[2]].code
        ]
      }
      this.$refs.AddOrEdit.visible = true
    },
    // 新增区域
    async addArea () {
      try {
        if (this.title === '新增点位') {
          await this.$refs.form.validate()
          this.formatArea()
          await addArea(this.form)
          this.$message.success('新增成功')
          this.$refs.AddOrEdit.visible = false
          this.getAreaList()
        } else {
          await this.$refs.form.validate()
          this.formatArea()
          const res = await editNode(this.form)
          console.log(res)
          if (res) {
            this.$message.success('修改成功')
            this.$refs.AddOrEdit.visible = false
            this.getAreaList()
          } else {
            this.$message.error('数据有误')
          }
        }
      } catch (err) {
        this.$message.error(err.response.data)
      }
    },
    // 格式地区
    formatArea () {
      const province = this.form.addr[0]
      const city = this.form.addr[1]
      const area = this.form.addr[2]
      this.form.addr =
        CodeToText[province] +
        '-' +
        CodeToText[city] +
        '-' +
        CodeToText[area] +
        '-' +
        this.form.remark
      this.form.areaCode = area
    }
  }
}
</script>

<style lang="less" scoped>
.header-search {
  .search-from {
    text-align-last: left;
    height: 100%;
    .area-search {
      width: 18%;
      margin: 0 10px 0 0;
      /deep/ .el-form-item__label {
        line-height: 64px !important;
      }
      /deep/ .el-form-item__content {
        line-height: 64px !important;
        .el-input__inner {
          height: 36px;
        }
      }
    }

    .search-btn {
      height: 100%;
      margin: 0;
      padding: 14px;
      .btn {
        display: flex;
        justify-content: center;
        align-items: center;
        width: 80px;
        height: 36px;
        background-color: #5f84ff;
        color: #fff;
        padding: 0;
      }
    }
  }
}
/deep/ .el-select,
.el-cascader {
  width: 100% !important;
}
</style>
